package com.dcivision.framework;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import org.mozilla.intl.chardet.nsPSMDetector;

public class CharsetDetector {

  public static final String REVISION = "$Revision: 1.5 $";


  public static String getCharset(InputStream f) throws ApplicationException {
    nsDetector det = new nsDetector(nsPSMDetector.ALL);
    StandardCharsetObserver scObserver = new StandardCharsetObserver();
    det.Init(scObserver);

    try {
      String result = null;
      BufferedInputStream imp = new BufferedInputStream(f);

      byte[] buf = new byte[1024];
      int len;
      boolean done = false;
      boolean isAscii = true;

      while ( (len = imp.read(buf, 0, buf.length)) != -1) {
        // Check if the stream is only ascii.
        if (isAscii) {
          isAscii = det.isAscii(buf, len);
        }

        // DoIt if non-ascii and not done yet.
        if (!isAscii && !done) {
          done = det.DoIt(buf, len, false);
        }
      }
      det.DataEnd();

      if (isAscii) {
        return ("ASCII");
      }

      if (!scObserver.isFound()) {
        String prob[] = det.getProbableCharsets();
        if (prob.length > 0) {
          result = prob[0];
        }
        for (int i = 0; i < prob.length; i++) {
          if ("BIG5".equalsIgnoreCase(prob[i])) {
            return(prob[i]);
          } else if ("GB2312".equalsIgnoreCase(prob[i])) {
            return(prob[i]);
          } else if ("UTF-8".equalsIgnoreCase(prob[i])) {
            return(prob[i]);
          }
        }
      }
      else {
        result = scObserver.getCharset();
      }

      return (result);
    }
    catch (Exception e) {
      return (null);
    }
  }

  public static void main(String argv[]) throws Exception {
    String filePath = "C:/char.txt";
    System.out.println(CharsetDetector.getCharset(new FileInputStream(filePath)));
  }
}

class StandardCharsetObserver implements nsICharsetDetectionObserver {
  private String result = null;
  private boolean found = false;

  public String getCharset() {
    return(this.result);
  }

  public boolean isFound() {
    return(this.found);
  }

  public void Notify(String charset) {
    this.result = charset;
    this.found = true ;
  }
}